import subprocess

def run_adb_command(ip, port, command_args):
    connect_command = ['adb', 'connect', f'{ip}:{port}']
    base_command = ['adb', '-s', f'{ip}:{port}']

    try:
        # Connect to the device
        subprocess.run(connect_command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        # Run the provided command
        full_command = base_command + command_args
        result = subprocess.run(full_command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        return result
    except subprocess.CalledProcessError as e:
        print(f"An error occurred: {e.stderr}")
        return None

def stop_app(device_ip, device_port, package_name):
    """停止指定的应用程序"""
    if is_app_installed(device_ip, device_port, package_name):
        result = run_adb_command(device_ip, device_port, ['shell', 'am', 'force-stop', package_name])
        if result:
            print(f'端口为{device_port}，已成功关闭{package_name}')
        else:
            print(f'端口为{device_port}，关闭{package_name}时遇到问题')
    else:
        print(f'{device_ip}:{device_port}这个设备未安装应用，无法关闭！')

def is_app_installed(device_ip, device_port, package_name):
    """检查应用程序是否已安装"""
    try:
        result = run_adb_command(device_ip, device_port, ["shell", "pm", "list", "packages", package_name])
        return package_name in result.stdout if result else False
    except subprocess.CalledProcessError as e:
        print(f"错误: 无法检查应用程序是否安装: {e}")
        return False

if __name__ == '__main__':
    # 安卓IP地址
    ip = "36.212.131.204"
    #安卓ip端口号
    port_list = [
        "40007"
    ]
    # 应用包名
    package_name = 'com.ss.android.ugc.aweme'

    for port in port_list:
        stop_app(ip, port, package_name)